package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.domain.LoginUser;
import cn.itsource.hrm.exception.GloabException;
import cn.itsource.hrm.mapper.LoginUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {
    
    @Autowired
    private LoginUserMapper loginUserMapper;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过用户名查询用户信息 
        LoginUser loginUser  = loginUserMapper.selectUserByName(username);
        if(loginUser==null){
            throw new GloabException("用户名不存在！");
        }
        // 查询一下用户的权限
        List<String> expressions =  loginUserMapper.selectPermissionByUser(loginUser.getId());
//        Collection<GrantedAuthority> authorities = new ArrayList<>();
//        expressions.forEach(exper ->{
//            authorities.add(new SimpleGrantedAuthority(exper));
//        });
        Collection<GrantedAuthority> authorities =  expressions.stream().map(exp ->  new SimpleGrantedAuthority(exp)).collect(Collectors.toList());
        
        UserDetails userDetails = new User(username,loginUser.getPassword(),authorities);
        return userDetails;
    }
}
